package com.yunkaweilai.android.activity.operation.consumption.room;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.operation.consumption.guadan.GuadanConfirmShopListActivity;
import com.yunkaweilai.android.activity.operation.consumption.guadan.GuadanListActivity;
import com.yunkaweilai.android.activity.operation.consumption.guadan.GuadanShopConsumptionActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.DialogMemberPayInterface;
import com.yunkaweilai.android.interfaces.MyDialogInterface;
import com.yunkaweilai.android.interfaces.RoomPriceInterface;
import com.yunkaweilai.android.interfaces.SimpleInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.guadan.GuadanInfoModel;
import com.yunkaweilai.android.model.room.RoomGuadanInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.DecimalUtil;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.ListViewForScroll;
import com.yunkaweilai.android.view.dialog.guadan.GuadanDelRemarkDialog1;
import com.yunkaweilai.android.view.dialog.guadan.GuadanReturnGoodsDialog;
import com.yunkaweilai.android.view.dialog.room.GuadanRoomCloseDialog;
import com.yunkaweilai.android.view.dialog.room.RoomUpdatePriceDialog;
import com.yunkaweilai.android.view.popup.ShopGuadanPopup;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 房台详情
 * Created by Administrator on 2017/8/14.
 */

public class RoomInfoActivity extends BaseActivity implements SimpleInterface, DialogMemberPayInterface, RoomPriceInterface, MyDialogInterface {

    public static final String ROOM_INFO_ID = "ROOM_INFO_ID";
    public static final String ROOM_INFO_NAME = "ROOM_INFO_NAME";
    public static final String ROOM_FLAG = "ROOM_FLAG";
    @BindView(R.id.id_tv_person)
    TextView idTvPerson;
    @BindView(R.id.id_tv_lable)
    TextView idTvLable;
    @BindView(R.id.id_tv_use_time)
    TextView idTvUseTime;
    @BindView(R.id.id_tv_price)
    TextView idTvPrice;
    @BindView(R.id.id_tv_room_price)
    TextView idTvRoomPrice;
    @BindView(R.id.id_tv_room_update)
    TextView idTvRoomUpdate;
    @BindView(R.id.id_tv_remarks)
    TextView idTvRemarks;
    @BindView(R.id.id_tv_remarks_update)
    TextView idTvRemarksUpdate;
    @BindView(R.id.id_listview)
    ListViewForScroll idListview;
    @BindView(R.id.id_btn_order)
    TextView idBtnOrder;
    @BindView(R.id.id_btn_turn_room)
    TextView idBtnTurnRoom;
    @BindView(R.id.id_btn_checkout)
    TextView idBtnCheckout;
    @BindView(R.id.id_btn_close_room)
    TextView idBtnCloseRoom;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_chronmeter)
    Chronometer idChronmeter;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_layout_fangfei)
    LinearLayout idLayoutFangfei;
    @BindView(R.id.id_fangfei_view)
    View idFangfeiView;

    private String gid;
    private String name;
    private Gson gson = new Gson();
    private RoomGuadanInfoModel roomGuadanInfoModel;
    private String status = "";
    private ArrayList<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean> list = new ArrayList<>();
    private CommonAdapter<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean> adapter;
    private TitleBuilder titleBuilder;
    private boolean isflag = true;

    public static void actionStart(Context context, String gid, String name, boolean isflag) {
        Intent intent = new Intent(context, RoomInfoActivity.class);
        intent.putExtra(ROOM_INFO_ID, gid);
        intent.putExtra(ROOM_FLAG, isflag);
        intent.putExtra(ROOM_INFO_NAME, name);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_info);
        ButterKnife.bind(this);
        gid = getIntent().getStringExtra(ROOM_INFO_ID);
        name = getIntent().getStringExtra(ROOM_INFO_NAME);
        isflag = getIntent().getBooleanExtra(ROOM_FLAG, true);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        titleBuilder = new TitleBuilder(mAc);
        titleBuilder.setLeftImage(R.mipmap.ic_go_back)
                .setTitleText(name)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isflag) {
                            RoomConsumptionActivity.actionStart(mAc, "1", "0");
                        } else {
                            finish();
                        }
                    }
                });
        initAdapter();
        initHttp();
        initClick();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (isflag) {
            idBtnTurnRoom.setVisibility(View.VISIBLE);
            idBtnCloseRoom.setVisibility(View.VISIBLE);
        } else {
            idBtnTurnRoom.setVisibility(View.GONE);
            idBtnCloseRoom.setVisibility(View.GONE);
        }

    }

    @Override
    public void onBackPressed() {
        if (isflag) {
            RoomConsumptionActivity.actionStart(mAc, "1", "0");
        } else {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.GUADAN_INFO_REFRESH) {
                if (event.flag) {
                    idMultipleStatusView.showLoading();
                    initHttp();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initClick() {
        //修改备注
        idTvRemarksUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShopGuadanPopup popup = new ShopGuadanPopup(mAc, "", roomGuadanInfoModel.getData().getInfo().getRemark(), "1", gid);
                popup.setmInflater(RoomInfoActivity.this);
                popup.showPopupWindow();
            }
        });
        //修改开台费
        idTvRoomUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoomUpdatePriceDialog dialog = new RoomUpdatePriceDialog(mAc, RoomInfoActivity.this, gid);
                dialog.show();
            }
        });
        //点单
        idBtnOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(status)) {
                    BaseApplication.cleanSelectedMaps();
                    GuadanShopConsumptionActivity.actionStart(mAc, gid);
                }

            }
        });
        //结账
        idBtnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(status)) {
                    GuadanConfirmShopListActivity.actionStart(mAc, gid, roomGuadanInfoModel.getData().getInfo().getFangfei(), "1");
                }
            }
        });
        //关台
        idBtnCloseRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(roomGuadanInfoModel.getData().getInfo().getStatus())) {
                    GuadanRoomCloseDialog dialog = new GuadanRoomCloseDialog(mAc, roomGuadanInfoModel.getData().getInfo().getGroup_id(),
                            "关台后请在挂单列表中的查看。", "当前未结账，是否确定关台？", gid);
                    dialog.show();
                } else {
                    GuadanRoomCloseDialog dialog = new GuadanRoomCloseDialog(mAc, roomGuadanInfoModel.getData().getInfo().getGroup_id(),
                            "请确认是否要关闭" + roomGuadanInfoModel.getData().getInfo().getGroup_info().getTitle() + "？", gid);
                    dialog.show();
                }
            }
        });
        //转台
        idBtnTurnRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(status)) {
                    RoomConsumptionActivity.actionStart(mAc, "2", gid);
                }
            }
        });


    }

    private void initAdapter() {
        adapter = new CommonAdapter<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean>(mAc, R.layout.item_list_guadan_shop, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean item, int position) {
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);
//
//                if (item.getSelectionIndex() == 1 && position == 1) {
//                    viewHolder.setVisible(R.id.id_view_line_bottom, true);
//                    viewHolder.setVisible(R.id.id_view_line_bottom2, false);
//                }

                viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
                viewHolder.setText(R.id.id_tv_price, item.getShop_discount_price() + "");
                viewHolder.setText(R.id.id_tv_return_num, "退货数：" + item.getRefund_num());
                TextView price2 = viewHolder.getView(R.id.id_tv_price2);
                price2.setText(item.getShop_price() + "");
                TextView price3 = viewHolder.getView(R.id.id_tv_price3);
                price3.setText("/" + item.getUnit() + " X" + item.getGoods_num());
                if (item.getShop_price().equals(item.getShop_discount_price())) {
                    price2.setVisibility(View.GONE);
                } else {
                    price2.setVisibility(View.VISIBLE);
                    price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                }

                View viewTop = viewHolder.getView(R.id.id_view_top);
                TextView idTvTop = viewHolder.getView(R.id.id_tv_top);
                int sPosition = getPosition(item.getSelectionIndex());
                if (sPosition < position) {
                    viewTop.setVisibility(View.GONE);
                    idTvTop.setVisibility(View.GONE);
                } else if (sPosition == position) {
                    viewTop.setVisibility(View.VISIBLE);
                    idTvTop.setVisibility(View.VISIBLE);
                    idTvTop.setText("第" + item.getSelectionIndex() + "次挂单");
                }
                TextView idTvReturn = viewHolder.getView(R.id.id_tv_return);
                if (DecimalUtil.subtract(item.getGoods_num(), item.getRefund_num()) > 0) {
                    idTvReturn.setVisibility(View.VISIBLE);
                } else {
                    idTvReturn.setVisibility(View.GONE);
                }
                viewHolder.getView(R.id.id_tv_return).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //退货
                        GuadanReturnGoodsDialog dialog1 = new GuadanReturnGoodsDialog(mAc, R.style.dialog, RoomInfoActivity.this, item.getO_gid(), item.getId(),
                                DecimalUtil.subtract(item.getGoods_num(), item.getRefund_num()), item.getGoods_name());
                        dialog1.show();
                    }
                });


            }
        };
        idListview.setAdapter(adapter);
    }

    //检验是否是第一个
    private int getPosition(int sIndex) {
        for (int i = 0; i < list.size(); i++) {
            GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean guadanGoodsListBean = list.get(i);
            if (guadanGoodsListBean.getSelectionIndex() == sIndex) {
                return i;
            }
        }
        return -1;
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.GUADAN_ROOM_INFO)
                .addParams("gid", gid)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            roomGuadanInfoModel = gson.fromJson(json, RoomGuadanInfoModel.class);
                            status = roomGuadanInfoModel.getData().getInfo().getStatus();
                            initView();
                            initShopHttp();
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }


    private void initShopHttp() {
        HttpRequest.postUrl(Api.GUADAN_INFO)
                .addParams("gid", gid)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            list.clear();
                            GuadanInfoModel guadanInfoModel = gson.fromJson(json, GuadanInfoModel.class);
                            List<GuadanInfoModel.DataBean.ListBean> biglist = guadanInfoModel.getData().getList();
                            for (int i = 0; i < biglist.size(); i++) {
                                GuadanInfoModel.DataBean.ListBean listBean = biglist.get(i);
                                for (int j = 0; j < listBean.getGuadanGoodsList().size(); j++) {
                                    GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean guadanGoodsListBean = listBean.getGuadanGoodsList().get(j);
                                    guadanGoodsListBean.setSelectionIndex(biglist.size() - i);
                                    list.add(guadanGoodsListBean);
                                }
                            }
                            Collections.sort(list, new Comparator<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean>() {
                                @Override
                                public int compare(GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean bean1, GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean bean2) {
                                    Integer id1 = bean1.getSelectionIndex();
                                    Integer id2 = bean2.getSelectionIndex();
                                    //可以按User对象的其他属性排序，只要属性支持compareTo方法
                                    return id2.compareTo(id1);
                                }
                            });
                            adapter.notifyDataSetChanged();
//                            Utils.showPartListView(idListview);
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        RoomGuadanInfoModel.DataBean.InfoBean info = roomGuadanInfoModel.getData().getInfo();
        idTvPerson.setText("开台操作员：" + roomGuadanInfoModel.getData().getInfo().getCreate_name() + "  " + info.getCreate_time());
        idTvLable.setText("标签：" + info.getLabel_name());

        idTvPrice.setText("消费金额：" + info.getPayment());
        idTvRoomPrice.setText("开台费：" + info.getFangfei());
        idTvRemarks.setText("消费备注：" + info.getRemark());

        if ("1".equals(info.getGroup_info().getIs_fangfei())) {
            idLayoutFangfei.setVisibility(View.VISIBLE);
            idFangfeiView.setVisibility(View.VISIBLE);
        } else {
            idLayoutFangfei.setVisibility(View.GONE);
            idFangfeiView.setVisibility(View.GONE);
        }

        if ("1".equals(info.getStatus())) {//还未结账
            idTvRoomUpdate.setVisibility(View.VISIBLE);
            idBtnOrder.setTextColor(getResources().getColor(R.color.white));
            idBtnTurnRoom.setTextColor(getResources().getColor(R.color.white));
            idBtnCheckout.setTextColor(getResources().getColor(R.color.white));
            idBtnCloseRoom.setTextColor(getResources().getColor(R.color.white));
            idBtnCloseRoom.setClickable(true);
            idBtnOrder.setClickable(true);
            idBtnTurnRoom.setClickable(true);
            idBtnCheckout.setClickable(true);
            idTvUseTime.setText("已使用时间：");
            idChronmeter.setFormat("%s");
            // 设置开始时间
            idChronmeter.setBase(SystemClock.elapsedRealtime() - info.getUserTime() * 1000);
            idChronmeter.start();
            titleBuilder.setRightText("作废").setRightOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GuadanDelRemarkDialog1 delRemarkDialog = new GuadanDelRemarkDialog1(mAc, gid, "房台作废", roomGuadanInfoModel.getData().getInfo().getGroup_id(),RoomInfoActivity.this);
                    delRemarkDialog.show();
                }
            });
        } else if ("2".equals(info.getStatus())) {//已经结账
            idTvRoomUpdate.setVisibility(View.GONE);
            idBtnOrder.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
            idBtnTurnRoom.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
            idBtnCheckout.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
            idBtnCloseRoom.setTextColor(getResources().getColor(R.color.white));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                idBtnOrder.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg2));
                idBtnTurnRoom.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg2));
                idBtnCheckout.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg2));
            }
            idBtnOrder.setClickable(false);
            idBtnTurnRoom.setClickable(false);
            idBtnCheckout.setClickable(false);
            idBtnCloseRoom.setClickable(true);
            idTvUseTime.setText("已使用时间：已结账");
            idChronmeter.setVisibility(View.GONE);

        }

    }

    @Override
    public void nothing() {
        idMultipleStatusView.showLoading();
        initHttp();
    }

    @Override
    public void passPay(String pass) {
        idTvRemarks.setText("消费备注：" + pass);
        roomGuadanInfoModel.getData().getInfo().setRemark(pass + "");

    }

    @Override
    public void ReturnPrice(String price) {
        String prices = Utils.ManageMoney(price);
        roomGuadanInfoModel.getData().getInfo().setFangfei(price);
        idTvRoomPrice.setText("开台费：" + prices);

    }

    @Override
    public void RightClick() {
        intent2Activity(GuadanListActivity.class);
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.GUADAN_LIST,true));
        finish();
    }

    @Override
    public void CancelClick() {

    }
}